import { ref } from 'vue'
import { API_URL } from '../config/apiConfig'
import { addAuthHeader } from './api/apiUtils'
import type { RuleTemplate } from '../types'
import { authStore } from './auth/store'
import { useRouter } from 'vue-router'

export function useRuleTemplateManagement() {
  const templateList = ref<RuleTemplate[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const downloadStatus = ref<{[key: string]: string}>({})

  const fetchTemplateList = async () => {
    loading.value = true
    error.value = null
    const router = useRouter()
    
    try {
      const response = await fetch(`${API_URL}/demo/rule-template/list`, addAuthHeader(
        {
          credentials: 'include',
          method: 'GET'
        }
      ))
      
      if (!response.ok) {
        if (response.status === 401 || response.status === 403) {
          // 清除认证状态
          authStore.clearAuth()
          // 重定向到登录页面
          router.push('/')
          return
        }
        throw new Error(`请求失败: ${response.status}`)
      }
      
      // 使用自定义解析函数确保id被转换为字符串
      const jsonText = await response.text()
      templateList.value = JSON.parse(jsonText, (key, value) => {
        // 对所有名为"id"的字段，无论其原始类型如何，都转换为字符串
        if (key === 'id') {
          return String(value)
        }
        return value
      })
      
    } catch (err) {
      console.error('获取规则模板列表失败:', err)
      error.value = '获取规则模板列表失败，请重试'
    } finally {
      loading.value = false
    }
  }

  const downloadTemplate = async (templateId: string) => {
    try {
      downloadStatus.value[templateId] = 'loading'
      console.log(`开始下载模板ID: ${templateId}`)
      
      // 确保templateId作为字符串使用，避免在URL中可能的精度问题
      const downloadUrl = `${API_URL}/demo/rule-template/${String(templateId)}/download`
      
      const response = await fetch(downloadUrl, addAuthHeader(
        {
          credentials: 'include',
          method: 'GET'
        }
      ))
      
      if (!response.ok) {
        const errorText = await response.text()
        console.error(`下载失败: ${response.status}`, errorText)
        throw new Error(`下载失败: ${response.status}`)
      }
      
      // 获取文件名
      const contentDisposition = response.headers.get('Content-Disposition')
      console.log('Content-Disposition:', contentDisposition)
      
      let filename = 'template.xlsx'
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
        if (filenameMatch && filenameMatch[1]) {
          filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''))
          console.log('解析出的文件名:', filename)
        }
      }
      
      // 检查响应类型
      const contentType = response.headers.get('Content-Type')
      console.log('Content-Type:', contentType)
      
      // 将响应转换为blob
      const blob = await response.blob()
      console.log('Blob大小:', blob.size, 'bytes')
      console.log('Blob类型:', blob.type)
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.style.display = 'none'
      a.href = url
      a.download = filename
      
      // 添加到DOM并触发点击
      document.body.appendChild(a)
      a.click()
      
      // 清理
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      
      downloadStatus.value[templateId] = 'success'
      console.log('下载成功:', filename)
      
      // 3秒后清除状态
      setTimeout(() => {
        if (downloadStatus.value[templateId] === 'success') {
          downloadStatus.value[templateId] = ''
        }
      }, 3000)
    } catch (err) {
      console.error('下载模板失败:', err)
      downloadStatus.value[templateId] = 'error'
      
      // 3秒后清除状态
      setTimeout(() => {
        if (downloadStatus.value[templateId] === 'error') {
          downloadStatus.value[templateId] = ''
        }
      }, 3000)
      
      alert('下载模板失败，请重试')
    }
  }

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    } catch (err) {
      return dateString
    }
  }

  const deleteTemplate = async (templateId: string) => {
    try {
      const response = await fetch(`${API_URL}/demo/rule/${templateId}`, addAuthHeader({
        method: 'DELETE'
      }))
      
      if (!response.ok) {
        throw new Error(`删除失败: ${response.status}`)
      }
      
      // 删除成功后刷新列表
      await fetchTemplateList()
      return true
    } catch (err) {
      console.error('删除模板失败:', err)
      return false
    }
  }

  return {
    templateList,
    loading,
    error,
    downloadStatus,
    fetchTemplateList,
    downloadTemplate,
    formatDate,
    deleteTemplate
  }
}